<template>
  <div class="flex gap-2">
    <h1 class="text-3xl ">{{ info.name }} <i @click="checkStatus" class="pi pi-sync" :class="{checking:'pi-spin'}"></i> </h1>
    <div class="grid grid-cols-1 grid-rows-2 gap-1 justify-center items-center">
      <Tag icon="pi pi-folder-open" :value="info.workDir" style="width: max-content"></Tag>
      <Tag
        icon="pi pi-file"
        severity="info"
        :value="info.execPath"
        style="width: max-content"
      ></Tag>
    </div>
    <Divider layout="vertical" />
    <div class="w-60 grid grid-cols-2 grid-rows-2 gap-1 justify-center items-center">
      <Button size="small" severity="success" @click="save">Save</Button>
      <Button size="small" severity="info" @click="test">Test</Button>
      <Button size="small" severity="success" v-if="!isRunning" @click="start">Start</Button>
      <Button size="small" severity="success" v-else @click="reload">Reload</Button>
      <Button size="small" severity="warn" @click="stop">Stop</Button>
    </div>
  </div>
  <Divider />
  <article class="mb-6 shadow-xl/30">
    <Panel toggleable>
      <template #header>
        <div class="flex items-center gap-2">
          <span class="font-bold">根配置</span>
        </div>
      </template>
      <Chip v-for="(i, index) in basicConfigs" :key="index">
        {{ i.code + '  ' + i.value + ';'
        }}<i class="pi pi-minus-circle" @click="basicConfigRemoveFn(i)" />
      </Chip>
      <Divider />
      <basic-config-add
        :options="basicConfigOptions"
        @confirm="basicConfigAddFn"
      ></basic-config-add>
    </Panel>
  </article>
  <Tabs value="0" class="shadow-xl/30">
    <TabList>
      <Tab value="0" as="div" class="flex items-center gap-2"
        ><span class="font-bold whitespace-nowrap">Http</span></Tab
      >
      <Tab value="1" as="div" class="flex items-center gap-2"
        ><span class="font-bold whitespace-nowrap">Stream</span></Tab
      >
    </TabList>
    <TabPanels>
      <TabPanel value="0">
        <http-config-component ref="httpConfigRef"></http-config-component>
      </TabPanel>
      <TabPanel value="1">
        <stream-config-component ref="streamConfigRef"></stream-config-component>
      </TabPanel>
    </TabPanels>
  </Tabs>
</template>
<script setup lang="ts">
import { useRoute } from 'vue-router'
import { onBeforeMount, ref, useTemplateRef } from 'vue'
import { useToast } from 'primevue/usetoast'
import type { BasicConfig, NginxInfo } from '@/types/dt/Dt.ts'
import BasicConfigAdd from '@/views/tools/nginx/detail-comps/basic-config-add.vue'
import HttpConfigComponent from '@/views/tools/nginx/detail-comps/http-config-component.vue'
import StreamConfigComponent from '@/views/tools/nginx/detail-comps/stream-config-component.vue'
import type { BasicConfigOption } from '@/views/tools/nginx/nginx-info.ts'
import { mainBasicOptions } from '@/views/tools/nginx/data/main_basic_options.ts'

const route = useRoute()
const toast = useToast()

const httpConfigRef = useTemplateRef('httpConfigRef')
const streamConfigRef = useTemplateRef('streamConfigRef')
const info = ref<NginxInfo>({
  id: '',
  name: '',
  workDir: '',
  execPath: '',
})

const isRunning = ref<boolean>(false)
const checking = ref<boolean>(false)

// 查询数据
const getDetail = async (id: string) => {
  try {
    info.value = await window.DefaultDt.getNginxInfoById(id)
    const detail = info.value.configDetail
    if (detail) {
      if (detail.http) {
        httpConfigRef.value!.setConfig(detail.http)
      }
      if (detail.stream) {
        streamConfigRef.value!.setConfig(detail.stream)
      }
      if (detail.basicConfigs) {
        basicConfigs.value = detail.basicConfigs
      }
    }
  } catch (e) {
    toast.add({
      summary: 'Get Nginx Info Error',
      detail: e,
    })
  }
}

// 根配置项增加
const basicConfigOptions = ref<BasicConfigOption[]>(mainBasicOptions)
const basicConfigs = ref<BasicConfig[]>([])
function basicConfigAddFn(e: BasicConfig) {
  basicConfigs.value.push(e)
}
function basicConfigRemoveFn(e: BasicConfig) {
  basicConfigs.value = basicConfigs.value.filter((item) => item !== e)
}

async function save() {
  const httpConfig = httpConfigRef.value!.getConfig()
  const streamConfig = streamConfigRef.value!.getConfig()
  try {
    const r = await window.DefaultDt.saveNginxDetail({
      id: route.query.id as string,
      basicConfigs: basicConfigs.value,
      http: httpConfig,
      stream: streamConfig,
    })
    if (r.code === 1) {
      toast.add({
        severity: 'success',
        summary: 'Success',
        detail: 'success',
        closable: true,
        life: 3000,
      })
    } else {
      toast.add({
        severity: 'error',
        summary: 'Error',
        detail: r.msg,
        closable: true,
        life: 10000,
      })
    }
  } catch (e) {
    toast.add({
      summary: 'save nginx detail error',
      detail: e,
    })
  }
}

async function test() {
  const r = await window.DefaultDt.testConfig(_id)
  if (r.code === 1) {
    toast.add({
      summary: 'Success',
      severity: 'success',
      detail: '配置无问题',
      life: 3000,
    })
  } else {
    toast.add({
      severity: 'error',
      summary: 'Error',
      detail: r.msg,
      life: 10000,
    })
  }
}
async function reload() {
  const r = await checkStatus()
  if (r.code === 1) {
    toast.add({
      summary: 'Success',
      severity: 'success',
      detail: '成功',
      life: 3000,
    })
  } else {
    toast.add({
      severity: 'error',
      summary: 'Error',
      detail: r.msg,
      life: 10000,
    })
  }
}

function checkStatus() {
  checking.value = true
  return window.DefaultDt.reloadNginx(_id).then((res) => {
    isRunning.value = res.code === 1
    return res
  }).finally(() => {
    checking.value = false
  })
}
async function start() {
  const r = await window.DefaultDt.startNginx(_id)
  if (r.code === 1) {
    toast.add({
      summary: 'Success',
      severity: 'success',
      detail: '启动成功',
      life: 3000,
    })
  } else {
    toast.add({
      severity: 'error',
      summary: 'Error',
      detail: r.msg,
      life: 10000,
    })
    checkStatus()
  }
}
async function stop() {
  const r = await window.DefaultDt.stopNginx(_id)
  if (r.code === 1) {
    toast.add({
      summary: 'Success',
      severity: 'success',
      detail: '成功',
      life: 3000,
    })
  } else {
    toast.add({
      severity: 'error',
      summary: 'Error',
      detail: r.msg,
      life: 10000,
    })
  }
  checkStatus()
}

let _id: string
onBeforeMount(async () => {
  const id = route.query.id
  if (typeof id !== 'string' || id === '') {
    toast.add({
      summary: 'parameter id must be string',
    })
    return
  }
  _id = id
  await getDetail(id)
  await checkStatus()
})
</script>

<style scoped lang="scss">
.path {
  border-radius: 15px;
  box-shadow:
    0 1px 2px 0 rgba(0, 0, 0, 0.04),
    0 1px 2px 0 rgba(0, 0, 0, 0.06);
}
</style>
